import sys
import pygame

from time import sleep
from src.roles.alien import Alien
from src.roles.plane import Plane
from src.roles.bullet import Bullet
from src.roles.button import Button
from src.manage.config import Settings
from src.manage.game_state import GameStates


class AlienInvasion:
    """
    管理游戏行为和资源
    """
    def __init__(self):
        """
        初始化并创建游戏资源
        """
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        pygame.display.set_caption("外星人入侵")

        self.states = GameStates()

        self.plane = Plane(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self._create_fleet()

        self.play_button = Button(self, "PLAY")

    def _check_events(self):
        """
        响应按键和鼠标事件
        点击`X`按钮退出游戏
        输入`q`退出游戏
        方向键控制飞机移动
        输入`x`发射子弹,在子弹消失之前只能发射三颗子弹
        """
        for event in pygame.event.get():
            trigger = event.type == pygame.KEYDOWN
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q: sys.exit()
                if event.key == pygame.K_x: self._fire()
                self._trigger_event(event.key, trigger)
            elif event.type == pygame.KEYUP:
                self._trigger_event(event.key, trigger)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _trigger_event(self, key, trigger):
        """
        触发飞机对应动作
        """
        action = Settings.events_map.get(key, "dont_move")
        setattr(self.plane, action, trigger)

    def _check_play_button(self,mouse_pos):
        """
        检测是否点击`PLAY`按钮
        """
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.states.game_active:
            self.states.reset_states()
            self.states.game_active = True

            self.aliens.empty()
            self.bullets.empty()

            self._create_fleet()
            self.plane.center_ship()
            # 开始游戏时隐藏鼠标指针
            pygame.mouse.set_visible(False)

    def _create_fleet(self):
        """
        创建外星人舰队
        """
        alien = Alien(self)
        settings = Settings()
        alien_width, alien_height = alien.rect.size
        avai_space_x = settings.width - (alien_width * 2)
        num_aliens_x = avai_space_x // (alien_width * 2)
        print(f"外星人尺寸:{alien.rect.size}")
        print(f"横轴可用像素空间:{avai_space_x}")
        print(f"每排有{num_aliens_x}个外星人")

        plane_height = self.plane.rect.height
        avai_space_y = (settings.height - (3 * alien_height) - plane_height)
        num_rows = avai_space_y // (2 * alien_height)
        print(f"飞机尺寸:{self.plane.rect}")
        print(f"纵轴可用像素空间:{avai_space_y}")
        print(f"外星人共有{num_aliens_x}列")

        for row_num in range(num_rows):    
            for alien_num in range(num_aliens_x):
                self._create_alien(alien_num, row_num)

    def _create_alien(self, alien_num,row_num):
        alien = Alien(self)
        alien_width, _ = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_num
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_num
        self.aliens.add(alien)

    def _fire(self):
        if len(self.bullets) < self.settings.bullet_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_plane(self):
        self.plane.update()

    def _update_screen(self):
        """
        更新屏幕上的图像,并切换到新屏幕
        """
        self.screen.fill(self.settings.bg_color)
        self.plane.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.aliens.draw(self.screen)
        if not self.states.game_active:
            self.play_button.draw_button()

        pygame.display.flip()

    def _check_bullet_alien_collisions(self):
        collisions =  pygame.sprite.groupcollide(
            self.bullets, self.aliens, True, True
        )

        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()

    def _update_bullets(self):
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
        self.bullets.update()
        self._check_bullet_alien_collisions()

    def _die(self):
        if self.states.planes_left > 0:
            self.states.planes_left -= 1
            self.aliens.empty()
            self.bullets.empty()
            
            self._create_fleet()
            self.plane.center_ship()

            sleep(0.5)
        else:
            self.states.game_active = False
            pygame.mouse.set_visible(True)

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()

        if pygame.sprite.spritecollideany(self.plane, self.aliens):
            self._die()
        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _check_aliens_bottom(self):
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._die()
                break

    def _change_fleet_direction(self):
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def start_game(self):
        """
        开启游戏的主循环
        """
        while True:
            self._check_events()
            if self.states.game_active:
                self._update_plane()
                self._update_bullets()
                self._update_aliens()
            self._update_screen()
